﻿using System;
using System.Collections.Generic;
using Xoohoo.Infrastructure;
using Xoohoo.Models;
using System.Security.Principal;

namespace Xoohoo.Models.ViewModels
{
    public class UserViewModel : IUser
    {
        #region Fields

        private readonly UserAnonymous _userAnonymous;
        private readonly User _user;

        #endregion

        #region Constructors

        public UserViewModel(IUser user)
        {
            InnerUser = user;
            Name = user.Name;

            if (user is UserAnonymous)
            {
                _userAnonymous = (UserAnonymous)user;

                UserGroup = new UserGroupBasic
                {
                    UserGroupID = Guid.NewGuid(),
                    UserGroupName = "Anonymous"
                };
                DisplayName = user.Name;
                Email = _userAnonymous.Email;
            }
            else if (user is User)
            {
                this._user = (User)user;

                UserGroup = this._user.UserGroup;
                DisplayName = this._user.DisplayName;
                Email = this._user.Email;
            }

        }

        #endregion

        #region Properties

        public IUser InnerUser { get; private set; }
        public string DisplayName { get; private set; }
        public UserGroupBasic UserGroup { get; set; }
        public string Email { get; private set; }

        #endregion

        #region IUser Members

        public string Name { get; private set; }
        public IIdentity Identity
        {
            get { return InnerUser.Identity; }
        }
        public bool IsAuthenticated { get { return Identity.IsAuthenticated; } }
        public IDictionary<string, object> AuthenticationValues {
            get
            {
                return InnerUser.AuthenticationValues;
            } 
        }
        public T Cast<T>() where T : class, IUser
        {
            return InnerUser as T;
        }
        public bool IsInUserGroup(string userGroupName)
        {
            return InnerUser.IsInUserGroup(userGroupName);
        }
        public bool IsInRole(string role)
        {
            return InnerUser.IsInRole(role);
        }
        public bool HasPermission(Guid permissionID)
        {
            return InnerUser.HasPermission(permissionID);
        }
        public bool HasPermission(string permissionName)
        {
            return InnerUser.HasPermission(permissionName);
        }

        #endregion

        #region Public Methods

        public User ToUserAuthenticated()
        {
            return _user;
        }
        public UserAnonymous ToUserAnonymous()
        {
            return _userAnonymous;
        }

        #endregion
    }
}
